#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

class ImageConverter
{
  ros::NodeHandle nh_;
  image_transport::ImageTransport it_;
  image_transport::Subscriber image_sub_;
  image_transport::Subscriber depth_sub_;

public:
  ImageConverter()
    : it_(nh_)
  {
    // 订阅RGB图像话题
    image_sub_ = it_.subscribe("/camera/color/image_raw", 1,
      &ImageConverter::imageCb, this);
    // 订阅深度图像话题
    depth_sub_ = it_.subscribe("/camera/depth/image_rect_raw", 1,
      &ImageConverter::depthCb, this);
  }

  ~ImageConverter()
  {
  }

  void imageCb(const sensor_msgs::ImageConstPtr& msg)
  {
    cv_bridge::CvImagePtr cv_ptr;
    try
    {
      cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
    }
    catch (cv_bridge::Exception& e)
    {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
    }

    // 显示RGB图像
    cv::imshow("RGB Image", cv_ptr->image);
    cv::waitKey(3);
  }

  void depthCb(const sensor_msgs::ImageConstPtr& msg)
  {
    cv_bridge::CvImagePtr cv_ptr;
    try
    {
      cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::TYPE_32FC1);
    }
    catch (cv_bridge::Exception& e)
    {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
    }

    // 将深度图转换为可视化格式
    cv::Mat normalized_depth;
    cv::normalize(cv_ptr->image, normalized_depth, 0, 255, cv::NORM_MINMAX, CV_8UC1);
    
    // 显示深度图像
    cv::imshow("Depth Image", normalized_depth);
    cv::waitKey(3);
  }
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "display_opencv");
  ImageConverter ic;
  cv::namedWindow("RGB Image", cv::WINDOW_AUTOSIZE);
  cv::namedWindow("Depth Image", cv::WINDOW_AUTOSIZE);
  ros::spin();
  cv::destroyAllWindows();
  return 0;
}